package com.limh.jkzs.activity

import android.app.Activity
import android.app.ProgressDialog
import android.bluetooth.BluetoothDevice
import android.content.Intent
import android.text.TextUtils
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.view.animation.LinearInterpolator
import com.limh.blehelper.Ble2Manager
import com.limh.blehelper.event.ConnectEvent
import com.limh.blehelper.event.ScanEvent
import com.limh.jkzs.R
import com.limh.jkzs.adapter.CommAdapter
import com.limh.jkzs.base.AppConfig
import com.limh.jkzs.base.BaseActivity
import com.limh.jkzs.util.Logs
import kotlinx.android.synthetic.main.activity_scan.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * Function:
 * author: limh
 * time:2018/1/18
 */
class ScanActivity : BaseActivity(), View.OnClickListener {

    private val REQUEST_ENABLE_BT = 1
    private lateinit var mAnimation: Animation
    private var isScaning = false

    private lateinit var dialog: ProgressDialog

    private val deviceBond = arrayListOf<BluetoothDevice>()
    private var bondAdapter: CommAdapter<BluetoothDevice>? = null
    private val deviceNoBond = arrayListOf<BluetoothDevice>()
    private var noBondAdapter: CommAdapter<BluetoothDevice>? = null

    override fun findViews() {
        setContentView(R.layout.activity_scan)
        dialog = ProgressDialog(this)
        dialog.setMessage("正在连接，请稍后...")
    }

    override fun initView() {
        imageScanClose.setOnClickListener(this)
        imageSearch.setOnClickListener(this)
        mAnimation = AnimationUtils.loadAnimation(this, R.anim.img_animation)
        val li = LinearInterpolator()
        mAnimation.interpolator = li

        deviceBond.addAll(Ble2Manager.getInstance().bondedDevices)
        if (deviceBond.size > 0) {
            txtPaired.visibility = View.VISIBLE
        } else {
            txtPaired.visibility = View.GONE
        }

        bondAdapter = object : CommAdapter<BluetoothDevice>(deviceBond, R.layout.view_item_blue_list) {
            override fun bindView(holder: ViewHolder, obj: BluetoothDevice) {
                if (TextUtils.isEmpty(obj.name) || "null" == obj.name)
                    holder.setVisibility(R.id.txt_item_blue_name, View.GONE)
                else
                    holder.setVisibility(R.id.txt_item_blue_name, View.VISIBLE)

                holder.setText(R.id.txt_item_blue_address, obj.address)
                holder.setText(R.id.txt_item_blue_name, obj.name)
            }
        }
        listPaired.adapter = bondAdapter
        listPaired.setOnItemClickListener { _, _, i, _ ->
            connect(deviceBond[i])
        }
        noBondAdapter = object : CommAdapter<BluetoothDevice>(deviceNoBond, R.layout.view_item_blue_list) {
            override fun bindView(holder: ViewHolder, obj: BluetoothDevice) {
                if (TextUtils.isEmpty(obj.name) || "null" == obj.name)
                    holder.setVisibility(R.id.txt_item_blue_name, View.GONE)
                else
                    holder.setVisibility(R.id.txt_item_blue_name, View.VISIBLE)

                holder.setText(R.id.txt_item_blue_address, obj.address)
                holder.setText(R.id.txt_item_blue_name, obj.name)
            }
        }
        listAvailable.adapter = noBondAdapter
        listAvailable.setOnItemClickListener { _, _, i, _ ->
            connect(deviceNoBond[i])
        }
    }

    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onScanStatus(scanEvent: ScanEvent) {
        when (scanEvent.scanStatus) {
            ScanEvent.SCAN_START -> {
                Logs.d(TAG, "EventBus start")
                deviceNoBond.clear()
                noBondAdapter!!.setData(deviceNoBond)
                imageSearch.startAnimation(mAnimation)
            }
            ScanEvent.SCAN_FOUND -> {
                Logs.d(TAG, "EventBus found=" + scanEvent.device!!.address + "  " + scanEvent.device.name + "  " + scanEvent.device.type + "  " + scanEvent.device.uuids + "  " + scanEvent.device.bluetoothClass)
                deviceNoBond.add(scanEvent.device)
                noBondAdapter!!.setData(deviceNoBond)
            }
            ScanEvent.SCAN_FINISH -> {
                Logs.d(TAG, "EventBus finish:" + scanEvent.scaningList.size)
                mAnimation.cancel()
                imageSearch.clearAnimation()
            }

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onConnStatus(connectEvent: ConnectEvent) {
        when (connectEvent.connStatus) {
            ConnectEvent.CONN_START -> {
                Logs.d(TAG, "ConnectEvent start")
                if (!dialog.isShowing) {
                    dialog.show()
                }

            }
            ConnectEvent.CONN_SUCCESS -> {
                showShort("连接成功")
                if (dialog.isShowing) {
                    dialog.dismiss()
                }
            }
            ConnectEvent.CONN_FAIL -> {
                showShort("连接失败")
                if (dialog.isShowing) {
                    dialog.dismiss()
                }
            }
            ConnectEvent.CONN_DISCONN -> {
                showShort("断开连接")
            }
        }
    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }

    override fun onClick(p0: View?) {
        when (p0!!.id) {
            R.id.imageScanClose -> finish()
            R.id.imageSearch -> {
                //开启蓝牙
                if (!isScaning) {
                    Ble2Manager.getInstance().scan()
                } else {
                    showLong("正在扫描,请稍后...")
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == Activity.RESULT_OK) {
                showShort("蓝牙已打开")
                Ble2Manager.getInstance().scan()
            }
        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    /**
     * 连接蓝牙
     */
    private fun connect(bluetoothLeDevice: BluetoothDevice) {
        Ble2Manager.getInstance().connect(bluetoothLeDevice, "00001101-0000-1000-8000-00805F9B34FB")
    }
}